import { CronJob } from 'cron';
import { app } from '../..';

export const clearVip = CronJob.from({
    cronTime: '0 0 0 */1 * *',
    onTick: async function () {
        try {
            const userSubscription = await app.prisma.$transaction(async (tx) => {
                // 查出所有过期的订阅
                const userSubscription = await tx.userSubscription.findMany({
                    where: {
                        endDate: {
                            lt: new Date()
                        }
                    },
                    include: {
                        user: true
                    }
                });
    
                // 删除用户的订阅
                await tx.userSubscription.deleteMany({
                    where: {
                        id: {
                            in: userSubscription.map(sub => sub.id)
                        }
                    }
                });
    
                // 调用次数重置
                await tx.user.updateMany({
                    where: {
                        id: {
                            in: userSubscription.map(sub => sub.userId)
                        }
                    },
                    data: {
                        callCount: 100
                    }
                });

                return userSubscription;
            });
            console.log('clear vip job success, total: ' + userSubscription.length);
        } catch (error) {
            console.log('clear vip job error: ' + error);
        }
    }
});
